//
//  picViewController.m
//  jiaxingchengtou
//
//  Created by michael on 2018/5/24.
//  Copyright © 2018年 czd. All rights reserved.
#import "pTableViewCell.h"

#import "webTableViewCell.h"
#import "tzTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "picTableViewCell.h"
#import "tongziViewController.h"
#import "OADetailDisPatchController.h"
#import "OADetailDisPatchCell.h"
#import "GDataDefines.h"
#import <QuickLook/QuickLook.h>
#import "OAHistroyViewController.h"
#import "OAAttachmentsModel.h"
#import "OASelectDepartmentController.h"
#import "OADepartmentModel.h"
#import "OADetailDispatchModel.h"
#import "OAReadRecordController.h"
#import "picViewController.h"

@interface picViewController ()<UITableViewDataSource,UITableViewDelegate,UIWebViewDelegate,QLPreviewControllerDataSource,QLPreviewControllerDelegate>
@property(nonatomic,strong)OADetailDispatchModel * detailPatchModel ;
@property(nonatomic,strong)NSMutableArray * attachmentArray; //附件
@property(nonatomic,strong)NSMutableArray * mainattachmentArray; //正文附件
@property(nonatomic,strong)NSString * attacmentURL;
@property(nonatomic,strong)NSMutableArray * contentsData;

@property(nonatomic,assign)BOOL isEditoring; //编辑中
@property(nonatomic,strong)NSMutableArray * departments;

@property(nonatomic,copy)NSString * infoString; //服务器返回字段 根据该字段跳转不同的界面
@property(nonatomic,copy)NSString * textString ; //记录填写的意见
@property(nonatomic,copy)NSString * body;
@property(nonatomic,strong)NSMutableArray * subItems;  //选中 需要提交得数据

@end

@implementation picViewController
-(NSMutableArray*)contentsData{
    if (_contentsData == nil) {
        _contentsData = [NSMutableArray array];
    }
    return _contentsData;
}

-(NSMutableArray*)attachmentArray{
    if (_attachmentArray ==nil) {
        _attachmentArray = [NSMutableArray array];
    }
    return _attachmentArray;
}
-(NSMutableArray*)mainattachmentArray{
    if (_mainattachmentArray == nil) {
        _mainattachmentArray = [NSMutableArray array];
    }
    return _mainattachmentArray;
}
-(NSMutableArray*)subItems{
    if (_subItems ==nil) {
        _subItems = [NSMutableArray array];
    }
    return _subItems;

}
- (void)viewDidLoad {
    [super viewDidLoad];
    // 判断接口
    self.view.backgroundColor = [UIColor whiteColor];
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight-kTopHeight) style:UITableViewStylePlain];
    _tableView.bounces = NO;
_tableView.dataSource = self;
_tableView.delegate = self;
[self.view addSubview:_tableView];
 _webView = [[UIWebView alloc]initWithFrame:self.view.frame];

 _webView.delegate = self;
//    _web.backgroundColor = [UIColor clearColor];
    _webView.hidden = YES;
        [self.view addSubview:_webView];

        [self _String];
     self.title = @"详情";
    
    
   
    self.tableView.hidden = YES;
 //加载网络数据
    [self loadData];
    
}
- (void)_String{
if ([self.type isEqualToString:@"jt"]){
self.method = @"frontlineContentFile";
self.url = KexchfrontlineURL;


}else if ([self.type isEqualToString:@"yx"]){
self.method = @"groupinformationContentFile";
self.url = KexchfrontlineURL;


}else if ([self.type isEqualToString:@"xm"]){
self.method = @"projectContentFile";
self.url = KexchfrontlineURL;


}
else if ([self.type isEqualToString:@"groupinformationContentFile"]){
self.method = @"groupinformationContentFile";
self.url = KexchfrontlineURL;

}else if ([self.type isEqualToString:@"frontlineContentFile"]){
self.method = @"frontlineContentFile";
self.url = KexchfrontlineURL;

}else if ([self.type isEqualToString:@"projectContentFile"]){
self.method = @"projectContentFile";
self.url = KexchfrontlineURL;

}else if ([self.type isEqualToString:@"leaderContentFile"]){
self.method = @"leaderContentFile";
self.url = KexchfrontlineURL;

}else if ([self.type isEqualToString:@"dutyContentFile"]){
self.method = @"dutyContentFile";
self.url = KexchfrontlineURL;

}
}
- (void)loadData{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    if ([_type isEqualToString:@"chaxun"]) {
       _array = @[@{@"userId":userId},@{@"unId":self.fileId},@{@"dbpath":_year}];

}else{
    _array = @[@{@"unId":self.fileId},@{@"userId":userId}];
  }
    [HttpTools postWithURL:self.url arrays:_array method:_method success:^(id JSON) {
    if([JSON isEqualToString:@"666"]){
    
    [self.view makeToast:@"对不起,您没有权限!"];
  [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

    }else{
   NSLog(@"====%@",JSON);
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        self.tableView.hidden = NO;
    if ([self.type isEqualToString:@"dengji"]) {
//    self.detailPatchModel = [self getDetailModel2:JSON];
} if ([self.type isEqualToString:@"zhuanfa"]||[self.type isEqualToString:@"dzgg"]||[self.type isEqualToString:@"jt"]||[self.type isEqualToString:@"xx"]||[self.type isEqualToString:@"gz"]||[self.type isEqualToString:@"yx"]||[self.type isEqualToString:@"xm"]||[self.type isEqualToString:@"groupinformationContentFile"]||[self.type isEqualToString:@"frontlineContentFile"]||[self.type isEqualToString:@"projectContentFile"]||[self.type isEqualToString:@"leaderContentFile"]||[self.type isEqualToString:@"dutyContentFile"]) {
    self.detailPatchModel = [self getDetailModel3:JSON];
}else{
//        self.detailPatchModel = [self getDetailModel1:JSON];
        }
        [self.tableView reloadData];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];
    
}
-(OADetailDispatchModel *)getDetailModel3:(NSString*)dataString;
{
    NSData * data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    OADetailDispatchModel * detailModel = [[OADetailDispatchModel alloc]init];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（Users）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（User）
    NSArray *rootData= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement *data in rootData) {
      
            GDataXMLElement *documentElement= [[data elementsForName:@"文档"] objectAtIndex:0];
            detailModel.document = [documentElement stringValue];
        
         GDataXMLElement *titletElement= [[data elementsForName:@"标题"] objectAtIndex:0];
            detailModel.title = [titletElement stringValue];
         GDataXMLElement *htmlElement= [[data elementsForName:@"html"] objectAtIndex:0];
         NSString *str1 = [[htmlElement stringValue] substringFromIndex:4];//截取掉下标5之前的字符串
            detailModel.html = str1;
        
            GDataXMLElement *filestep= [[data elementsForName:@"填写意见环节"] objectAtIndex:0];
            detailModel.flow = [filestep stringValue];
        
            GDataXMLElement *fileId= [[data elementsForName:@"唯一标识"] objectAtIndex:0];
            detailModel.fileId = [fileId stringValue];
        
        
    }
    //index。seston = 2
    for (GDataXMLElement * subData in rootData) {
        NSArray * tempArray = [subData elementsForName:@"数据实体"];
        for (GDataXMLElement * element in tempArray) {
            NSArray *array = [element elementsForName:@"附件"];
            for (GDataXMLElement * data in array) {
                OAAttachmentsModel * attachModel = [[OAAttachmentsModel alloc]init];
                GDataXMLElement * nameElement = [[data elementsForName:@"名称"] objectAtIndex:0];
                NSString *  name = [nameElement stringValue];
                attachModel.attachmentsTitle = name;
                
                GDataXMLElement * contentElement = [[data elementsForName:@"内容"] objectAtIndex:0];
                NSString *  content = [contentElement stringValue];
                attachModel.attachmentsURL = content;
                
                [self.attachmentArray addObject:attachModel];
            }
        }
    }
    
    for (GDataXMLElement * subData in rootData) {
        NSArray * tempArray = [subData elementsForName:@"图片"];
        for (GDataXMLElement * element in tempArray) {
            NSArray *array = [element elementsForName:@"附件"];
            for (GDataXMLElement * data in array) {
                OAAttachmentsModel * attachModel = [[OAAttachmentsModel alloc]init];
                GDataXMLElement * nameElement = [[data elementsForName:@"名称"] objectAtIndex:0];
                NSString *  name = [nameElement stringValue];
                attachModel.attachmentsTitle = name;
                 GDataXMLElement * picElement = [[data elementsForName:@"图"] objectAtIndex:0];
                NSString *  pic = [picElement stringValue];
                attachModel.pic = pic;
                GDataXMLElement * contentElement = [[data elementsForName:@"内容"] objectAtIndex:0];
                NSString *  content = [contentElement stringValue];
                attachModel.attachmentsURL = content;
                
                [self.mainattachmentArray addObject:attachModel];
            }
        }
    }
    
    return detailModel;
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    switch (section) {
        case 0:
            return self.detailPatchModel.titleArray.count;
            break;
        case 1:
            return self.mainattachmentArray.count;
        case 2:
            return 1;
             case 3:
            return self.attachmentArray.count;
        default:
            return 1;
            break;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
     static NSString *identifier=@"UITableViewCellIdentifierKey7";
    picTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier];

if(!cell){
        cell=[[picTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier];
    }
     
   NSString * allString = self.detailPatchModel.titleArray[indexPath.row];
        cell.detailModel = self.detailPatchModel;
        cell.allString = allString;
    

                  return cell;
   
    }else if (indexPath.section == 2) {
     static NSString *identifier2=@"UITableViewCellIdentifierKey2";
    webTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifier2];

if(!cell){
        cell=[[webTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:identifier2];
    }
     
   NSString * allString = self.detailPatchModel.formArray[indexPath.row];
        cell.detailModel = self.detailPatchModel;
//        cell.allString = allString;
    

                  return cell;
   
    }
    else{

        if (indexPath.section == 1) {
            static NSString * cellIdentifier = @"cellIdentifier";
            pTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            if (cell == nil) {
                cell = [[pTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
          
            }
                              OAAttachmentsModel * model = self.mainattachmentArray[indexPath.row];
                              cell.model = model;



            return cell;
            
        }else{
            static NSString * cellIdentifier = @"cellId";
            UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            }
            OAAttachmentsModel * model = self.attachmentArray[indexPath.row];
            cell.textLabel.text = model.attachmentsTitle;
            cell.textLabel.font = [UIFont systemFontOfSize:14];
            cell.textLabel.numberOfLines = 0;
            cell.textLabel.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
            return cell;

        }
          }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

      if (indexPath.section == 0) {
            NSString * allString = self.detailPatchModel.titleArray[indexPath.row];
 NSArray * tempArray = [allString componentsSeparatedByString:@"##"];

        CGFloat height =  [allString boundingRectWithSize:CGSizeMake(KScreenWidth - 20, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil].size.height;
        if (height < 44) {
            height = 44;
        }  if ([tempArray.firstObject isEqualToString:@"内容"]) {
                        return height + 10;

        }else{
                return height + 10;

        }
        }else if (indexPath.section == 2) {
            NSString * allString = self.detailPatchModel.formArray[indexPath.row];
 NSArray * tempArray = [allString componentsSeparatedByString:@"##"];

        CGFloat height =  [allString boundingRectWithSize:CGSizeMake(KScreenWidth - 20, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil].size.height;
        if (height < 44) {
            height = 44;
        }  if ([tempArray.firstObject isEqualToString:@"内容"]) {
//                        return height + 10;
                 return 400;


        }else{
//                return height + 10;
                 return 400;

        }
        }else if(indexPath.section==1){
           OAAttachmentsModel * model = self.mainattachmentArray[indexPath.row];
                float i  = [model.pic floatValue];
        return KScreenWidth*i+30 ;
        }
   
    
    else{
        return 54;
    }
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
 if (section==3) {
        UIView * bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 30)];
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10,5, KScreenWidth, 21)];
        label.text = @"附件";
         UIView *lineview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, .5)];
        lineview.backgroundColor = [UIColor colorWithHexString:@"C8C7CC"];
if (_attachmentArray.count>0) {
            [bgView addSubview:lineview];

}else{
bgView.hidden = YES;

}
//        label.backgroundColor = [UIColor grayColor];
//        label.font = [UIFont systemFontOfSize:14];
//        label.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
 label.font = [UIFont systemFontOfSize:16];
        label.textColor = [UIColor blackColor];
        [bgView addSubview:label];
//         if (_attachmentArray.count>0) {
//            OAAttachmentsModel * model = self.attachmentArray[0];
//            if ([model.attachmentsTitle length]>0) {
//        return bgView;
//
//}
//else{
//        return nil;
//
//}
//}else{
//     if (!(self.attachmentArray.count>0)) {
//            label.hidden = YES;
//        }else{
//            label.hidden = NO;
//        }
//         if (!(self.attachmentArray.count>0)) {
//        return nil;
//        }else{
//        return bgView;
//        }
//        }
        return bgView;

}else{
return nil;
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{


   if (section==3) {
       return 30;

   }else{
          return 0.01;

   
   }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if (indexPath.section == 3){
        OAAttachmentsModel * model = self.attachmentArray[indexPath.row];
        [self openFileURL:model.attachmentsURL];
// fujianwebViewController *vc = [[fujianwebViewController alloc]init];
//        vc.url = model.attachmentsURL;
//        [self.navigationController pushViewController:vc animated:YES];
    }
}
-(void)openFileURL:(NSString*)url{
    NSString * stringurl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    self.attacmentURL =  [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[url lastPathComponent]]; //附件路径
 
    if ([self isExtistFilePathWithFileName:[[NSURL URLWithString:stringurl] lastPathComponent]]) { //已经存在附件
        QLPreviewController *previewoCntroller = [[QLPreviewController alloc] init] ;
        previewoCntroller.delegate=self;
        previewoCntroller.dataSource=self;
        previewoCntroller.navigationItem.rightBarButtonItem=nil;
                                    previewoCntroller.hidesBottomBarWhenPushed = YES;

        [self.navigationController pushViewController: previewoCntroller animated:YES];
        
    }else{
        MBProgressHUD * hud  =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.labelText = @"下载中...";
        NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:stringurl]];
        [self.webView loadRequest:request];
    }
    
}

#pragma mark PreviewDataSource
//第一个方法是设定一组文档浏览的个数，会影响到在文档预览中的上/下一页。
-(NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller {
    return 1;
}
//第二个方法是指定文档预览的文件路径
-(id<QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index {
    
    return [NSURL fileURLWithPath:self.attacmentURL];
}

-(BOOL)isExtistFilePathWithFileName:(NSString*)fileName{
    NSString * file = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString * filePath = [file stringByAppendingPathComponent:fileName];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath] && fileName.length != 0) {
        return YES;
    }else{
        return NO;
    }
    
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSURL * requestedURL = [request URL];
    NSData * fileData = [[NSData alloc] initWithContentsOfURL:requestedURL];
    NSString * filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
     [fileData writeToFile:[filePath stringByAppendingPathComponent:[requestedURL lastPathComponent]] atomically:YES];
      return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
    
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    QLPreviewController *previewoCntroller = [[QLPreviewController alloc] init] ;
    previewoCntroller.delegate=self;
    previewoCntroller.dataSource=self;
    [self.navigationController pushViewController: previewoCntroller animated:YES];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
